<template>
  <div>
    <van-nav-bar title="项目" left-arrow @click-left="onClickLeft" />
    <van-cell :border="false" title="项目名称" :value="projectObj.name"/>
    <van-cell :border="false" title="业态" :value="projectObj.operation"/>
    <div class="van-cell van-field">
      <div class="van-cell__title van-field__label">
        <span>一级分类</span>
      </div>
      <div class="van-cell__value" @click="showSheet1 = true">
        <div class="van-field__body">
          <div class="van-field__control">{{level1Obj.level1 || ''}}</div>
          <div class="van-field__right-icon">
            <i class="van-icon van-icon-arrow-down"></i>
          </div>
        </div>
      </div>
    </div>
    <div v-for="(item, i) in photo1" :key="level1Obj.level1 + item.label + i">
      <van-swipe-cell :right-width="60">
        <div class="van-cell van-field" style="margin-bottom: 10px;">
          <div class="van-cell__title van-field__label">
            <span>照片描述</span>
          </div>
          <div class="van-cell__value">
            <div class="van-field__body">
              <input :value="item.label" :data-i="i" @change="onInputChange1" type="text" class="van-field__control" placeholder="请输入照片描述" />
            </div>
          </div>
        </div>
        <van-button square slot="right" type="danger" text="删除" @click="delPhoto(i, 1)" />
      </van-swipe-cell>
      <van-uploader multiple :after-read="afterRead1" :max-size="maxSize" @oversize="oversize" :name="i + ''">
        <div class="van-uploader__wrapper">
          <div class="van-image van-uploader__preview van-image-zindex"
            v-for="(item1,index) in item.list"
            :key="item1.src + index"
            @click.stop.prevent="imgClick(item1.src, item.list)"
          >
            <img :src="item1.src" class="van-image__img" style="object-fit: cover;">
            <van-icon name="clear" @click.stop.prevent="delImg(i, index, 1)" />
          </div>
          <div class="van-image van-uploader__preview" style="box-sizing:border-box;border: 1px dashed #e5e5e5;text-align:center;line-height:80px;">
            <van-icon name="plus" />
          </div>
        </div>
      </van-uploader>
    </div>
    <div class="button-wrap btn-wrap">
      <van-button type="primary" @click="addPhoto(1)" style="margin-right:10px;">添加照片</van-button>
      <van-button type="primary" @click="save(1)">保存</van-button>
    </div>
    <div class="van-cell van-field" v-if="level2Obj.level2">
      <div class="van-cell__title van-field__label">
        <span>二级分类</span>
      </div>
      <div class="van-cell__value" @click="showSheet2 = true">
        <div class="van-field__body">
          <div class="van-field__control">{{level2Obj.level2 || ''}}</div>
          <div class="van-field__right-icon">
            <i class="van-icon van-icon-arrow-down"></i>
          </div>
        </div>
      </div>
    </div>
    <div v-for="(item, i) in photo2" :key="level2Obj.level2 + item.label + i">
      <van-swipe-cell :right-width="60">
        <div class="van-cell van-field" style="margin-bottom: 10px;">
          <div class="van-cell__title van-field__label">
            <span>照片描述</span>
          </div>
          <div class="van-cell__value">
            <div class="van-field__body">
              <input :value="item.label" :data-i="i" @change="onInputChange2" type="text" class="van-field__control" placeholder="请输入照片描述" />
            </div>
          </div>
        </div>
        <van-button square slot="right" type="danger" text="删除" @click="delPhoto(i, 2)" />
      </van-swipe-cell>
      <van-uploader multiple :after-read="afterRead2" :max-size="maxSize" @oversize="oversize" :name="i + ''">
        <div class="van-uploader__wrapper">
          <div class="van-image van-uploader__preview van-image-zindex"
            v-for="(item1,index) in item.list"
            :key="item1.src + index"
            @click.stop.prevent="imgClick(item1.src, item.list)"
          >
            <img :src="item1.src" class="van-image__img" style="object-fit: cover;">
            <van-icon name="clear" @click.stop.prevent="delImg(i, index, 2)" />
          </div>
          <div class="van-image van-uploader__preview" style="box-sizing:border-box;border: 1px dashed #e5e5e5;text-align:center;line-height:80px;">
            <van-icon name="plus" />
          </div>
        </div>
      </van-uploader>
    </div>
    <div class="button-wrap btn-wrap" v-if="level2Obj.level2">
      <van-button type="primary" @click="addPhoto(2)" style="margin-right:10px;">添加照片</van-button>
      <van-button type="primary" @click="save(2)">保存</van-button>
    </div>
    <div class="button-wrap">
      <van-button style="width:90%" type="primary" @click="goToExport">导出</van-button>
    </div>
    <van-action-sheet v-model="showSheet1" :actions="actions1" @select="onSelect1"/>
    <van-action-sheet v-model="showSheet2" :actions="actions2" @select="onSelect2"/>
  </div>
</template>
<script>
import { getProjectList, saveLevel1Photo, saveLevel2Photo, getLevel1Photo, getLevel2Photo } from "@/utils/storage.js";
import { compressImageCanvas } from "@/utils/file.js";
import myStorage from "@/utils/myStorage";
import { randomN } from '@/utils/random.js';

import vanNavBar from "vant/lib/nav-bar";
import "vant/lib/nav-bar/style";
import vanActionSheet from "vant/lib/actionsheet";
import "vant/lib/actionsheet/style";
import vanCell from "vant/lib/cell";
import "vant/lib/cell/style";
import vanButton from "vant/lib/button";
import "vant/lib/button/style";
import vanSwipeCell from "vant/lib/swipe-cell";
import "vant/lib/swipe-cell/style";
import vanIcon from "vant/lib/icon";
import "vant/lib/icon/style";
import "vant/lib/field/style";
import vanUploader from "vant/lib/uploader";
import "vant/lib/uploader/style";
export default {
  components: {
    vanNavBar,
    vanActionSheet,
    vanCell,
    vanButton,
    vanIcon,
    vanUploader,
    vanSwipeCell
  },
  data() {
    return {
      maxSize: 10 * 1024 * 1024, // 最大上传限制10M
      projectlist: [],
      projectIndex: 0,
      projectObj: {},
      showSheet1: false,
      showSheet2: false,
      level1Index: 0,
      level2Index: 0,
      photo1: [],
      photo2: [],
    };
  },
  computed: {
    level1Obj() {
      const level1list = this.projectObj.level1list || [];
      return level1list[this.level1Index] || {};
    },
    level2Obj() {
      const level2list = this.level1Obj.level2list || [];
      return level2list[this.level2Index] || {};
    },
    actions1() {
      const level1list = this.projectObj.level1list || [];
      return level1list.map((t) => {
        return { name: t.level1 };
      });
    },
    actions2() {
      const level2list = this.level1Obj.level2list || [];
      return level2list.map((t) => {
        return { name: t.level2 };
      });
    }
  },
  created() {
    this.projectlist = getProjectList();
    this.projectIndex = parseInt(this.$route.params.i) || 0;
    this.projectObj = this.projectlist[this.projectIndex] || {};
    // 渲染照片描述
    this.randerPhoto(0, 0);
  },
  methods: {
    oversize() {
      this.$toast('请上传小于6M大小的图片');
    },
    onClickLeft() {
      this.$router.go(-1);
    },
    listMap(arr) {
      return arr.map((p) => {
        return {
          label: p.label,
          list: (p.list || []).map((l) => {
            return {
              item: l.item,
              src: myStorage.getItem(l.item)
            }
          })
        };
      });
    },
    randerPhoto(lv1Index, lv2Index) {
      const level1list = this.projectObj.level1list || [];
      const level1Obj = level1list[lv1Index];
      const photo1 = level1Obj.photolist || [];
      this.photo1 = this.listMap(photo1);
      const level2list = level1Obj.level2list || [];
      const level2Obj = level2list[lv2Index] || {};
      const photo2 = level2Obj.photolist || [];
      this.photo2 = this.listMap(photo2);
    },
    onSelect1(obj, index) {
      this.level1Index = index;
      this.level2Index = 0;
      this.showSheet1 = false;

      this.projectlist = getProjectList();
      this.projectObj = this.projectlist[this.projectIndex] || {};  
      
      const photo1 = this.level1Obj.photolist || [];
      this.photo1 = this.listMap(photo1);
      const level2list = this.level1Obj.level2list || [];
      const level2Obj = level2list[0] || {};
      const photo2 = level2Obj.photolist || [];
      this.photo2 = this.listMap(photo2);
    },
    onSelect2(obj, index) {
      this.level2Index = index;
      this.showSheet2 = false;

      this.projectlist = getProjectList();
      this.projectObj = this.projectlist[this.projectIndex] || {};

      const level2list = this.level1Obj.level2list || [];
      const level2Obj = level2list[index] || {};
      const photo2 = level2Obj.photolist || [];
      this.photo2 = this.listMap(photo2);
    },
    goToExport() {
      const projectlist = getProjectList();
      const i = projectlist.findIndex(t => t.name === this.projectObj.name);
      this.$router.push(`/layout/export/${i}`);
    },
    imgClick(src, list) {
      const arr = list.map(t => t.src);
      const i = arr.findIndex(t => t === src);
      this.$imagePreview({
        images: arr,
        startPosition: i,
        onClose() {}
      });
    },
    onInputChange1(e) {
      const index = Number(e.target.dataset.i);
      this.photo1[index].label = e.target.value;
    },
    onInputChange2(e) {
      const index = Number(e.target.dataset.i);
      this.photo2[index].label = e.target.value;
    },
    addPhoto(type) {
      this['photo' + type].push({ label: '', list: [] });
    },
    delImg(photoIndex, listIndex, type) {
      if (!this.check(type)) {
        return;
      }
      var arr = this['photo'+type][photoIndex].list;
      var delList = arr.splice(listIndex, 1);
      delList.forEach((t) => {
        myStorage.removeItem(t.item);
      })
      this['photo'+type][photoIndex].list = arr;
      if (type === 1) {
        saveLevel1Photo(this.projectObj.name, this.level1Obj.level1, this.photo1);
        // this.photo1 = getLevel1Photo(this.projectObj.name, this.level1Obj.level1);
      } else if (type === 2) {
        saveLevel2Photo(this.projectObj.name, this.level1Obj.level1, this.level2Obj.level2, this.photo2);
        // this.photo2 = getLevel2Photo(this.projectObj.name, this.level1Obj.level1, this.level2Obj.level2);
      }
    },
    delPhoto(photoIndex, type) {
      if (!this.check(type)) {
        return;
      }
      this.$dialog.confirm({
        title: '删除确认',
        message: '是否确定删除该照片描述？'
      }).then(() => {
        const list = this['photo'+type][photoIndex].list || [];
        list.forEach((t) => {
          myStorage.removeItem(t.item);
        })
        const arr = this['photo'+type];
        arr.splice(photoIndex, 1);
        this['photo'+type] = arr;
        if (type === 1) {
          saveLevel1Photo(this.projectObj.name, this.level1Obj.level1, this.photo1);
          // this.photo1 = getLevel1Photo(this.projectObj.name, this.level1Obj.level1);
        } else if (type === 2) {
          saveLevel2Photo(this.projectObj.name, this.level1Obj.level1, this.level2Obj.level2, this.photo2);
          // this.photo2 = getLevel2Photo(this.projectObj.name, this.level1Obj.level1, this.level2Obj.level2);
        }
      }).catch(() => {});
    },
    iterator(i, list, index, type) {
      let _this = this;
      if (i >= list.length) {
        return;
      }
      var reader = new FileReader();
      reader.readAsDataURL(list[i].file);
      reader.onload = function() {
        // 使用canvas压缩base64文件
        compressImageCanvas(this.result, function (newSrc) {
          const last = randomN(6) + (new Date().getTime() + '').substr(-6) + randomN(6);
          let item = `${_this.projectObj.name}^${_this.level1Obj.level1}^描述^${last}`;
          if (type === 2) {
            item = `${_this.projectObj.name}^${_this.level1Obj.level1}^${_this.level2Obj.level2}^描述^${last}`;
          }
          // 文件上传的时候存入缓存中  --  这样优化了保存卡顿，删除卡顿的现象，缺点是如果用户添加了图片却不保存，那么数据在缓存中，并不会被清理
          myStorage.setItem(item, newSrc);
          if (_this['photo' + type][index].list) {
            _this['photo' + type][index].list.push({src: newSrc, item});
          } else {
            _this.$set(_this['photo' + type][index], 'list', [{src: newSrc, item}]);
          }
          _this.iterator(i + 1, list, index, type);
        });
      }
    },
    afterRead1(file, obj) {
      let fileList = file instanceof Array ? file : [file];
      let index = Number(obj.name);
      this.iterator(0, fileList, index, 1);
    },
    afterRead2(file, obj) {
      let fileList = file instanceof Array ? file : [file];
      let index = Number(obj.name);
      this.iterator(0, fileList, index, 2);
    },
    check(type) {
      const arr = this['photo' + type] || [];
      for(let i = 0; i < arr.length; i++) {
        let photoDesc = arr[i];
        if (!photoDesc.label.trim()) {
          this.$toast('照片描述不能为空');
          return false;
        }
        if (arr.filter((t,index) => { return index > i; }).some(t => t.label.trim() === photoDesc.label.trim())) {
          this.$toast('不能保存重复的照片描述');
          return false;
        }
      }
      return true;
    },
    save(type, callback) {
      if (!this.check(type)) {
        return;
      }
      const arr = this['photo' + type] || [];
      if (type === 1) {
        saveLevel1Photo(this.projectObj.name, this.level1Obj.level1, arr);
      } else if (type === 2) {
        saveLevel2Photo(this.projectObj.name, this.level1Obj.level1, this.level2Obj.level2, arr);
      }
      if (callback) {
        callback();
      }
      this.$toast.success('保存成功');
    }
  }
};
</script>
<style lang="less" scoped>
.button-wrap {
  text-align: center;
  padding: 10px 0;
  .van-button {
    width: 30%;
    border-radius: 10px;
  }
}
.btn-wrap{
  padding: 6px 0;
  .van-button {
    height: 30px;
    line-height: 28px;
  }
}
.van-uploader {
    margin-left: 15px;
    .van-uploader__input{
      display: none;
    }
}
.van-image {
    position: relative;
    display: inline-block;
    vertical-align: top;
    .van-icon-clear{
      position: absolute;
      right: -5px;
      top: -5px;
      font-size: 20px;
    }
}
.van-image-zindex{
  z-index: 1;
}
.van-uploader__preview {
    width: 80px;
    height: 80px;
    margin: 0 10px 10px 0;
    .van-image__img{
      display: block;
    width: 100%;
    height: 100%;
    }
}
</style>
